#include "threadPool.h"

int cdFunc(dirStack_t *dirstack, const char* destdir, MYSQL *sql,
    const char *username) {
  int i = 0, j = 0;
  char data[128];
  if (destdir[0] == '/') {  // 从根目录开始的路径
    cleanDirStack(dirstack);
    i = 1;
  } else if (destdir[0] == '\0') {  // 路径为空
    cleanDirStack(dirstack);
  } else if (destdir[0] == '~') {
    if (destdir[1] == '/') {  // 从家目录开始的路径
      cleanDirStack(dirstack);
      i = 2;
    } else if (destdir[1] == '\0') {  // 路径为~
      cleanDirStack(dirstack);
      i = 1;
    }
  }
  MYSQL_RES *result;
  MYSQL_ROW row;
  char sql_query[256] = {0};
  while (destdir[i] != '/' && destdir[i] != '\0') {
    memset(data, 0, sizeof(data));
    j = 0;
    while (destdir[i] != '/' && destdir[i] != '\0') {
      data[j] = destdir[i];
      ++i;
      ++j;
    }
    memset(sql_query, 0, sizeof(sql_query));
    snprintf(sql_query, sizeof(sql_query),
             "SELECT id FROM fileSystem WHERE filename = '%s' AND username = '%s' AND parent_id = %d",
             data, username, dirstack->top->data);
    if (strcmp(data, ".") == 0) {
    } else if (strcmp(data, "..") == 0) {
      popDirStack(dirstack);
    } else {
      if (0 != mysql_query(sql, sql_query)) {
        fprintf(stderr, "cdFunc() query failed: %s\n", mysql_error(sql));
        return -1;
      }
      if (NULL == (result = mysql_store_result(sql))) {
        fprintf(stderr, "cdFucn() no result\n");
        return -1;
      }
      if (NULL != (row = mysql_fetch_row(result))) {
        char *endptr;
        errno = 0;
        int id = (int)strtol(row[0], &endptr, 10);
        if (errno != 0 || *endptr != '\0') {
          fprintf(stderr, "cdFunc() cast failed: %s\n", row[0]);
          return -1;
        } else {
          printf("cdFunc() get id: %d successful\n", id);
          pushDirStack(dirstack, id);
        }
      }
      mysql_free_result(result);
    }
    if (destdir[i] == '/') {
      ++i;
    }
  }
  return 0;
}
